package com.geek.netty.outbound.httpclient4;

import org.jetbrains.annotations.NotNull;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @program geek
 * @description: factory
 * @author: chanzhugang
 * @create: 2021/04/04 12:48
 */
public class NamedThreadFactory implements ThreadFactory {

    private final ThreadGroup group;

    private final AtomicInteger threadNum = new AtomicInteger(1);

    private final String namePrefix;

    private final boolean daemon;

    public NamedThreadFactory(String namePrefix, boolean daemon) {
        this.daemon = daemon;
        SecurityManager manager = System.getSecurityManager();
        group = manager != null ? manager.getThreadGroup() : Thread.currentThread().getThreadGroup();
        this.namePrefix = namePrefix;
    }

    public NamedThreadFactory(String namePrefix) {
        this(namePrefix, false);
    }

    @Override
    public Thread newThread(@NotNull Runnable r) {
        Thread thread = new Thread(group, r, namePrefix + "-thread-" + threadNum.getAndIncrement(), 0);
        thread.setDaemon(daemon);
        return thread;
    }
}